package com.ffox.config;

import com.ffox.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security 配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityServiceConfig {
    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityServiceConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 1. 禁用CSRF，配置CORS
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))

                // 2. 禁用HTTP Basic认证
                .httpBasic(basic -> basic.disable())

                // 3. 无状态会话
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )

                // 4. 配置SecurityContext持有策略
                .securityContext(securityContext -> securityContext
                        .securityContextRepository(securityContextRepository())
                )

                // 5. 关键：授权配置
                .authorizeHttpRequests(auth -> auth
                        // 5.1 开放无需认证的接口
                        .requestMatchers(
                                // 原有开放接口
                                "/login/userLogin",
                                "/login/studentLogin",
                                "/login/schoolLogin",
                                "/login/platformLogin",
                                "/login/userInsert",
                                "/login/schoolInsert",
                                "/login/platformInsert",
                                "/login/studentInsert",
                                "/ws/**",
                                "/app/**"
                        ).permitAll()

                        // 5.2 角色控制接口
                        .requestMatchers("/homework/**","/course/**")
                        .hasAnyRole("PLATFORM", "USER", "STUDENT", "SCHOOL")
                        .requestMatchers("/login/userDelete/**","/userTeacherSubject/**", "/userGroupChat/**")
                        .hasAnyRole("PLATFORM", "USER")
                        .requestMatchers("/login/studentDelete/**")
                        .hasAnyRole("PLATFORM", "STUDENT")
                        .requestMatchers("/login/schoolDelete/**", "/schoolTeacher/**", "/schoolStudent/**")
                        .hasAnyRole("PLATFORM", "SCHOOL")
                        .requestMatchers("/login/platformDelete/**", "/platformSchool/**")
                        .hasRole("PLATFORM")

                        // 5.3 其他请求需认证
                        .anyRequest().authenticated()
                )

                // 6. 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .headers(headers -> headers
                        .frameOptions(frame -> frame.disable()));

        System.out.println("SecurityConfig被触发了");
        return http.build();
    }

    /**
     * 配置SecurityContextRepository
     */
    @Bean
    public SecurityContextRepository securityContextRepository() {
        return new DelegatingSecurityContextRepository(
                new RequestAttributeSecurityContextRepository(),
                new HttpSessionSecurityContextRepository()
        );
    }

    /**
     * 修复CORS配置：移除通配符，指定具体前端源
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowedOrigins(Arrays.asList("http://127.0.0.1:8866"));


        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));


        configuration.setAllowedHeaders(Arrays.asList("Authorization",
                "Content-Type",
                "Upgrade",
                "Connection",
                "Sec-WebSocket-Key",
                "Sec-WebSocket-Version","*"));

        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        // 显式指定常用头
         Arrays.asList("Authorization", "Content-Type", "X-Requested-With");

        // 4. 允许携带凭证
        configuration.setAllowCredentials(true);

        // 5. 预检请求缓存时间
        configuration.setMaxAge(3600L);

        // 6. 应用到所有路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    /**
     * 密码加密器
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}